# -*- coding: utf-8 -*-

from odoo import models, fields, api,_
import logging
_logger = logging.getLogger(__name__)
import json
import werkzeug.utils
from odoo.exceptions import UserError, ValidationError
# import xmltodict
import requests
import urllib
import urllib2

class SaleSettingWizard(models.TransientModel):
    _name = 'sale.sys.settings'
    _description = u'基本设置'
    _inherit = 'res.config.settings'

    fen_level = fields.Selection([
        ('1',u'一级'),
        ('2',u'二级'),
        ('3',u'三级')
    ],u'分销商层级',default='1')
    first = fields.Float(u'一级分销商提成(金额)')
    second = fields.Float(u'二级分销商提成(金额)')
    third = fields.Float(u'三级分销商提成(金额)')

    income = fields.Many2one("account.account",u'业务收入科目')
    recipt = fields.Many2one("account.account",u'收款账户科目')
    commission = fields.Many2one("account.account",u'分销佣金科目')
    payable_1 = fields.Many2one("account.account",u'计提佣金科目')

    payable_2 = fields.Many2one("account.account",u'应付提成科目')

    mall_name = fields.Char('商城名称', help='显示在小程序顶部')
    app_id = fields.Char('appid')
    secret = fields.Char('secret')
    wechat_pay_id = fields.Char('微信支付商户号')
    wechat_pay_secret = fields.Char('微信支付商户秘钥')



    @api.one
    @api.constrains('first', 'second','third')
    def _check_ticheng(self):
        if self.first < 0:
            raise ValidationError(_('提成必须大于零'))
        if self.second < 0:
            raise ValidationError(_('提成必须大于零'))
        if self.third < 0 :
            raise ValidationError(_('提成必须大于零'))

    @api.multi
    def cancel(self):
        # ignore the current record, and send the action to reopen the view
        actions = self.env['ir.actions.act_window'].search([('res_model', '=', self._name)], limit=1)
        if actions:
            return actions.read()[0]
        return {}


    # @api.multi
    def save_param(self):
        # self.ensure_one()
        # super(SaleSettingWizard,self).execute()
        Param = self.env["ir.config_parameter"]
        Param.set_param('fen_level',self.fen_level)
        Param.set_param('first',self.first)
        Param.set_param('third',self.third)
        Param.set_param('second',self.second)

        Param.set_param('income',self.income.id)
        Param.set_param('recipt',self.recipt.id)
        Param.set_param('commission',self.commission.id)
        Param.set_param('payable_1',self.payable_1.id)
        Param.set_param('payable_2',self.payable_2.id)

        #---------微信小程序的设置---------------------------------
        Param.set_param('mall_name',self.mall_name)
        Param.set_param('app_id',self.app_id)
        Param.set_param('secret',self.secret)
        Param.set_param('wechat_pay_id',self.wechat_pay_id)
        Param.set_param('wechat_pay_secret',self.wechat_pay_secret)
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }
        # Param.set_param('pay',config.pay.id)

    def get_default_delivery_config(self, fields):
        Param = self.env["ir.config_parameter"]
        return{
            'fen_level': Param.get_param('fen_level',default='2'),
            'first': float(Param.get_param('first')),
            'second': float(Param.get_param('second')),
            'third': float(Param.get_param('third')),

            'income': int(Param.get_param('income')),
            'recipt': int(Param.get_param('recipt')),
            'commission': int(Param.get_param('commission')),
            'payable_1': int(Param.get_param('payable_1')),
            'payable_2': int(Param.get_param('payable_2')),

            'mall_name':   Param.get_param('mall_name',default='分销系统'),
            'app_id':   Param.get_param('app_id',default='app_id_xxxx'),
            'secret': Param.get_param('secret', default='sevret_xxxxx'),
            'wechat_pay_id': Param.get_param('wechat_pay_id', default='pay_id_xxxxx'),
            'wechat_pay_secret': Param.get_param('wechat_pay_secret', default='secret_xxxxxx')
        }

class sale_sys(models.Model):
    _inherit = 'sale.order'

    name = fields.Char(string=u"订单编号",readonly=True,copy=False,index=True)
    fen_company = fields.Many2one('res.partner',u'企业分销商')
    first_sale = fields.Many2one('res.partner',u'一级分销商')
    first_sale_money = fields.Float(u'一级分销商提成')
    second_sale = fields.Many2one('res.partner',u'二级分销商')
    second_sale_money = fields.Float(u'二级分销商提成')
    third_sale = fields.Many2one('res.partner',u'三级分销商')
    third_sale_money = fields.Float(u'三级分销商提成')
    statement = fields.Selection([
        ('0',u'待付款'),
        ('1',u'待收货'),
        ('2',u'已完成'),
        ('3',u'已取消'),
    ],u'微信订单状态',default='0')
    delivery_no = fields.Char(u'快递单号')
    delivery_code = fields.Selection([
        ('shunfeng',u'顺丰'),
        ('zhongtong',u'中通'),
        ('shentong',u'申通'),
        ('yuantong',u'圆通'),
        ('yunda',u'韵达'),
        ('tiantian',u'天天')
    ],u'快递公司')
    delivery_info = fields.Text(compute='_get_delivery_info_JSON')
    delivery_state = fields.Selection([
        ('no',u'未签收'),
        ('yep',u'已签收')
    ],u'物流状态',default='no')
    payment_ids = fields.One2many('wechat_mall.payment','order_id',u"支付记录")

    @api.model
    def create(self,vals):
        vals['name'] = self.env['ir.sequence'].next_by_code('wechat_mall.order_num')
        return super(sale_sys,self).create(vals)

    @api.one  #抓取物流信息
    def _get_delivery_info_JSON(self):
        self.delivery_info = json.dumps(False)
        info = {'title': '', 'outstanding': True, 'content': [], 'sale_id': self.id}
        if self.delivery_no and self.delivery_code:
            url = "http://www.kuaidi100.com/query?type=%s&postid=%s" % (self.delivery_code, int(self.delivery_no))
            response = urllib2.urlopen(url)
            html = response.read().decode('utf-8')
            target = json.loads(html)
            status = target['status']
            if status == '200':
                data = target['data']
                for i in range(len(data)):
                    info['content'].append({
                        'time':data[i]['time'],
                        'state':data[i]['context']
                    }) 

        self.delivery_info = json.dumps(info)

    @api.multi #定时任务
    def test_icron(self):
        order = self.env['sale.order'].search([])
        _logger.info(order)
        if order:
            for i in order:
                if i.delivery_state == 'no':
                    i._get_delivery_info_JSON()

class salesys_product(models.Model):
    _inherit = "product.template"


    product_info = fields.Html(u"产品详情")
    product_no = fields.Integer(u'在手数量')